/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ServerFrame;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
/**
 *
 * @author Denver A Guitiw
 * @author
 * @author
 */
public class ServerFrame extends java.awt.Frame{

    /**
     * Creates new form ServerFrame
     */

    public ServerFrame(){
    	this.frame =frame;
        setTitle("Server");
        initComponents();
        setLocationRelativeTo(null);
    }
    public void createConnection(){
    	name = JOptionPane.showInputDialog(frame,"Enter your name.","Server");
 		boolean confirm=true;
 		String ipadd=null;
 		try {
		 	// Create a server socket
			Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    		while (e.hasMoreElements()){
        		NetworkInterface n = e.nextElement();
        	//	System.out.println(n.getName());
        		Enumeration<InetAddress> ee = n.getInetAddresses();
        		while (ee.hasMoreElements()){
            		inetaddress = ee.nextElement();
           			char  inet =inetaddress.getHostAddress().toString().charAt(1);
            		if(inet==('9')){
         				ipadd =  inetaddress.getHostAddress().toString();
            			break;
            		}
        			else if(confirm==false){
        				inetadd = JOptionPane.showInputDialog(frame,"Create server via: ",ipadd);
        				}
        			}
    			}
    		inetaddress.getByName(inetadd);
            serverSocket = new ServerSocket(3339,30,inetaddress);
    		TableModel.setValueAt(name+" - Server",0,0);
    		TableModel.setValueAt(inetaddress,0,1);
    		TableModel.setValueAt("online",0,2);
    		broadCastTextArea.append("Server started at " + new Date() + '\n');
			broadCastTextArea.append("Server Address: " +inetaddress+ '\n');
			broadCastTextArea.append(name +" has joinded the group " + '\n');
    		multisocket = new MulticastSocket(3338);
 			group = InetAddress.getByName("230.0.1.2");
 			multisocket.joinGroup(group);
 			runBroadCast();
 			new Thread(new acceptClient()).start();
 			}
		 catch(IOException ex) {
		 	broadCastTextArea.append("Establishing Server Error: " + ex);
		 	inetadd = JOptionPane.showInputDialog(frame,"Create server via: ",ipadd);
		 	confirm=false;
		 	if(inetadd==null||inetadd.equals("")){
        			return;
        		}
        	createConnection();
        		}
		 }
    	public class  acceptClient implements Runnable{
    		public void run(){
			try{
 				while(true){
 					new ClientHandler(serverSocket.accept()).start();
 					broadCastTextArea.append("Client Accepted"+'\n');
 					}
 				}
 		catch(IOException ex) {
			broadCastTextArea.append("AcceptClient Error: "+ex);
			retry++;
			if(retry==2){
				return;
				}
			broadCastTextArea.append(" exit" + "\n");
	 		}
	 	}
	 }
	 public void UpdateList(){
	 		for(int x=0;x!=data.length;x++){
 				if(data[x][0]==(null)){
 					data[x][0] = new DataObject(ClientName);
 					data[x][1] = new DataObject(ClientIPadress);
 					data[x][2] = new DataObject("Online");
 					data[x][3] = new DataObject(totalSocket);
 					return;
 					}
 				if(mytable.getValueAt(x,0).toString().equalsIgnoreCase(ClientName)){
 					data[x][0] = new DataObject(ClientName);
 					data[x][1] = new DataObject(ClientIPadress);
 					data[x][2] = new DataObject("Online");
 					data[x][3] = new DataObject(totalSocket);;
 					break;
 					}
 			}
	 }
	 public void runBroadCast(){
	 	broadCastTextArea.append("Listening BroadCast" + "\n");
 		new Thread(new listenBroadCast()).start();
 	}

 	public class SendFileToClient implements Runnable{ // sends file
 		public void run(){
 		try {

		      while (true) {
		      ServerSocket servsock = new ServerSocket(123);
		      Socket sock = servsock.accept();	//---------waits for client to receive
		      chatTextArea.append("file sent" + "\n");

		      byte[] mybytearray = new byte[(int) file.length()];
		      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		      bis.read(mybytearray, 0, mybytearray.length);
		      OutputStream os = sock.getOutputStream();
		      os.write(mybytearray, 0, mybytearray.length);
		      os.flush();
		      sock.close();
	    }
 		}
 			catch (IOException e) {
        }
 		}

 	}
 	public void	newSocketAccept(){
 		try {
 			newSocket[totalSocket] = serverSocket.accept();
 		}
 		catch (IOException e) {
            System.out.println("err: broadCast 10101 "+ e);
           }
 	}
 	public void broadCast(){ //Sends BroadCast to clients
 		if(multisocket==null){
 			return;
 		}
 		try {
 			message = name+": "+message;
            System.out.println("broadcasting");
            buf = message.getBytes();
		    DGsocket = new DatagramSocket();
            packet = new DatagramPacket(buf, buf.length, group, 3338);
               // broadcasting message
                multisocket.send(packet);
   			}
   			catch (IOException e) {
                System.out.println("err: broadCast 10101 "+ e);
            	}
 		}
 		public class listenBroadCast implements Runnable{ // Listens any clients BroadCast
 		public void run(){
 		try {
        MulticastSocket mcsocket = new MulticastSocket(3338);
        InetAddress address = InetAddress.getByName("230.0.1.2");
		mcsocket.joinGroup(address);
        DatagramPacket packet;
		while(true) {
	    	byte[] buf = new byte[256];
            packet = new DatagramPacket(buf, buf.length);
            mcsocket.receive(packet);

            message = new String(packet.getData(), 0, packet.getLength());
            broadCastTextArea.append(message + '\n');
		}
            }
   			catch (IOException e) {
                System.out.println("err: listenBroadCast 2101 "+ e);
            	}
 		}
 	}
	  public class ClientHandler extends Thread {
		private Socket socket = null;

	 public ClientHandler(Socket socket) {
		super("ClientHandler");
		this.socket = socket;
    		}
	 public void run(){
 		try{
		outputstream = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(
                   socket.getInputStream()));

 		ClientName = in.readLine();
 		ClientIPadress =  in.readLine();
 		outputstream.println(Totalrow);
 		UpdateList();
 		System.out.println("name: "+ClientName + "  IP: " +ClientIPadress);
 		getList();
	 	mytable.updateUI();
 		System.out.println("name: "+ClientName + "  IP: " +ClientIPadress);

 		while ((message = in.readLine()) != null) {
 				chatTextArea.append(message + "\n");
 				outputstream.println(message);
 			}
 			System.out.println("wait InputStream");
 		}
 		catch (IOException ex) {
 		try{
 			outputstream.close();
 			in.close();
 		}
 		catch (IOException exe) {}
 		broadCastTextArea.append("Client has disconnected: ");;
 			}
 		}
	 }
	 public void getList(){
	 	int x, y=0;
	 	for(x=0;x!=data.length;x++){
 			if(data[x][0]==null){
 				return;
 			}
 			for(y=0;y!=4;y++){
 			outputstream.println(data[x][y].toString());
 			}
 		}
	 }
	  public class newSocketClientHandler implements Runnable{
	  	public void run(){
	  		try{
				outputstreamTSC = new PrintWriter(newSocket[usersSelectedSocket].getOutputStream(), true);
          		inTSC = new BufferedReader(new InputStreamReader(
                   newSocket[usersSelectedSocket].getInputStream()));
 				while ((message = inTSC.readLine()) != null||(message)!=null) {
 					chatTextArea.append(message + "\n");
 					outputstreamTSC.println(message);
 					}
			}
 			catch (IOException ex) {
 			try{
 				outputstreamTSC.close();
 				inTSC.close();
 			}
 			catch (IOException exe) {}
 				broadCastTextArea.append("Client has disconnected: ");;
 				}
 			}
		}
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        broadCastTextArea = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TableModel = new DefaultTableModel();
        mytable = new javax.swing.JTable(TableModel);
        javax.swing.JButton jButton2 = new javax.swing.JButton();
        RunServerButton = new javax.swing.JButton();
        javax.swing.JButton ShutDownButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        javax.swing.JButton chatButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        chatTextArea = new javax.swing.JTextArea();
        SelectedUserLabel = new javax.swing.JLabel();
        javax.swing.JButton sendChatButton = new javax.swing.JButton();
        chatTextField = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        BroadCastTextField = new javax.swing.JTextField();
        javax.swing.JButton BroadCastButton = new javax.swing.JButton();
        javax.swing.JButton OptionButton = new javax.swing.JButton();
		jPanel5.setBorder(BorderFactory.createTitledBorder("Users Information"));

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        data = new DataObject[30][4];
        readFile();
        broadCastTextArea.setColumns(20);
        broadCastTextArea.setLineWrap(true);
        broadCastTextArea.setRows(5);
        jScrollPane1.setViewportView(broadCastTextArea);


        mytable.setMaximumSize(new java.awt.Dimension(247, 280));
        mytable.setMinimumSize(new java.awt.Dimension(45, 300));
        mytable.setOpaque(false);
        jScrollPane2.setViewportView(mytable);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane2)
                .addGap(21, 21, 21))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addGap(11, 11, 11))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );

        jButton2.setText("Settings");

        RunServerButton.setText("Run Server");
        RunServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RunServerButtonactionPerformed(evt);
            }
        });

        ShutDownButton.setText("Shut down");
        ShutDownButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShutDownButtonActionPerformed(evt);
                
                broadCastTextArea.setText("");
                
                JOptionPane.showMessageDialog(frame,"Press Ok to Shut Down...");

				System.exit(0);
									

            }
        });

        chatButton.setText("Chat");
        chatButton.setActionCommand("chatClient");
        chatButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ChatButtonActionPerformed(evt);
            }
        });

        chatTextArea.setColumns(20);
        chatTextArea.setRows(5);
        jScrollPane4.setViewportView(chatTextArea);

        SelectedUserLabel.setText(SelectedUser);

        sendChatButton.setText("Send");
        sendChatButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendChatButtonChatButtonActionPerformed(evt);
            }
        });
        chatTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chatTextFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(SelectedUserLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addGap(183, 183, 183))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chatButton)
                .addGap(18, 18, 18)
                .addComponent(sendChatButton)
                .addContainerGap())
            .addComponent(chatTextField, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(jScrollPane4)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(SelectedUserLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chatTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sendChatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(chatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(60, 60, 60))
        );

        BroadCastButton.setText("BroadCast");
        BroadCastButton.setToolTipText("");
        BroadCastButton.setActionCommand("BrCast");
        BroadCastButton.setName("broadCastButton"); // NOI18N
        BroadCastButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BroadCastButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addComponent(BroadCastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(BroadCastButton)
                .addContainerGap(12, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BroadCastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BroadCastButton))
                .addContainerGap())
        );

        OptionButton.setText("Send Files");
		  OptionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OptionButtonActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(3, 3, 3))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addGap(6, 6, 6)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(66, 66, 66)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(RunServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                            .addComponent(ShutDownButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(OptionButton, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))
                        .addGap(72, 72, 72))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(255, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)
                        .addGap(46, 46, 46))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(RunServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(OptionButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(30, 30, 30)
                        .addComponent(ShutDownButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(63, 63, 63)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(210, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(260, Short.MAX_VALUE)))
        );

        add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }



    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
     private void OptionButtonActionPerformed(java.awt.event.ActionEvent evt){
     		int retrnValue = filechoose.showOpenDialog(null);
            if (retrnValue == JFileChooser.APPROVE_OPTION) {
                file = filechoose.getSelectedFile();
            }
            new Thread(new SendFileToClient()).start();
            outputstream.println("New incoming file, Click Accept Button to confirm "+'\n');
     }
    private void BroadCastButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BroadCastButtonActionPerformed
        // TODO add your handling code here:
       message = BroadCastTextField.getText();
       BroadCastTextField.setText(null);
	   broadCast();
    }//GEN-LAST:event_BroadCastButtonActionPerformed
    private void ShutDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShutDownButtonActionPerformed
        // TODO add your handling code here:
        try{
        	socket.close();
        	serverSocket.close();
        	multisocket.close();
        }
        catch(Exception e){
        	System.out.println("Error closing: " + e);
        }
    }//GEN-LAST:event_ShutDownButtonActionPerformed
    private void ChatButtonActionPerformed(java.awt.event.ActionEvent evt){//GEN-FIRST:event_ChatButtonActionPerformed
       	try{
       		mytable.updateUI();
       	}
       	catch (Exception e){
       		System.out.println("Chat button error: "+e);
       	}
    }//GEN-LAST:event_ChatButtonActionPerformed
	private void RunServerButtonactionPerformed(java.awt.event.ActionEvent evt){
        // TODO add your handling code here:
        createConnection();
  		mytable.updateUI();
       // RunServerButton.setEnabled(false);
    }
    private void sendChatButtonChatButtonActionPerformed(java.awt.event.ActionEvent evt){
   			servermessage = chatTextField.getText();
   			outputstream.println(name+": "+servermessage);
   			chatTextArea.append(name+": "+servermessage);
       	 	chatTextField.setText(null);
   	}
    private void chatTextFieldActionPerformed(java.awt.event.ActionEvent evt){
			servermessage	= chatTextField.getText();
			chatTextArea.append(name+": "+servermessage);
			outputstream.println(name+": "+servermessage);
       	 	chatTextField.setText(null);
   	}
    public void sendToSelectedClient(){
   		try{
	   		PrintWriter out = new PrintWriter(newSocket[usersSelectedSocket].getOutputStream(), true);
    		servermessage = name +": "+ servermessage;
	  		out.println(servermessage);
	  		chatTextArea.append(servermessage+'\n');
	  		servermessage=null;
    		}
    		catch(Exception e)	{
    			System.out.println("error: Run Server to client  " + e + "  " + '\n');
    			chatTextArea.append("sendToSelectedClient error: "+e+ +'\n');
    	}
    	}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ServerFrame().setVisible(true);
            }
        });
    }
   	class DefaultTableModel  extends AbstractTableModel {
		  String[] columns = {"Name","IP Address",
                              "Status","Message"};
    	public int getColumnCount() {
            return currCol;
        }
		public TableColumn addColumn(TableColumn ob){
			return ob;
		}
        public int getRowCount() {
            return data.length;
        }
        public String getColumnName(int cols) {
           return columns[cols];
      }
       public Object getValueAt(int rows, int cols) {
            return data[rows][cols];
        }
        public boolean isCellEditable(int row, int col) {
        	 SelCol=mytable.getSelectedColumn();
        	 SelRow = mytable.getSelectedRow();
             return false;
        }
        public void setValueAt(Object value, int rows, int cols) {
            if (DEBUG){
                System.out.println("Setting value at " + rows + "," + cols
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

          	data[rows][cols] = new DataObject(value);
            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
       		}
        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
   	}
   		public void InputData(){
	    	int inttemp=0;
	    	try{
    	  	for(Totalrow=0;(line = br.readLine())!=null;Totalrow++) {
                StringTokenizer stkr = new StringTokenizer(line.trim(), ",");
                data[Totalrow][0] = new DataObject((stkr.nextToken()));
                data[Totalrow][1] = new DataObject(stkr.nextToken());
                data[Totalrow][2] = new DataObject(stkr.nextToken());
                data[Totalrow][3] = new DataObject(stkr.nextToken());
    	  }
    		fis.close();
    		br.close();
    	}
    	catch (Exception e){
    	}
		}
   		public void readFile(){
		try{

		// To read the input file
    	 fis = new FileInputStream(openFileName);
     	 br = new BufferedReader(new InputStreamReader(fis));
		}
		catch (Exception e){
			System.out.println("exception=== "+e);
		}
			InputData();
		}
	public class DataObject{
	DataObject intevalue,StrValue,ObValue;
	Object value;

	public DataObject(Object value){
		this.value = value;
	}
	public String toString(){
    	return  ("" + value);
    }
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    	private javax.swing.JTextArea broadCastTextArea;
    	private javax.swing.JTextArea chatTextArea;
    	private javax.swing.JLabel SelectedUserLabel;
    	private javax.swing.JPanel jPanel1;
    	private javax.swing.JPanel jPanel2;
    	private javax.swing.JPanel jPanel3;
    	private javax.swing.JPanel jPanel4;
    	private javax.swing.JPanel jPanel5;
    	private javax.swing.JScrollPane jScrollPane1;
    	private javax.swing.JScrollPane jScrollPane2;
    	private javax.swing.JScrollPane jScrollPane4;
    	private javax.swing.JTextField chatTextField;
    	private javax.swing.JTextField BroadCastTextField;
    	private	javax.swing.JButton RunServerButton;
    	private	DefaultTableModel TableModel;
    	private boolean DEBUG = false;
    	private InetAddress inetaddress;
   		private String name;
   		int currCol=4;
   		private JFrame optionFrame = new JFrame("Options");
   		private DatagramPacket packet;
		private	DatagramSocket DGsocket = null;
		private	static JFrame frame = new JFrame("Server");
		private Socket socket=null;
		private Socket[] newSocket = new Socket[30];
		private int chatSocketNo=0;
		private String message;
        private ServerSocket serverSocket;
       	private InetAddress group;
       	private MulticastSocket multisocket;
       	private byte[] buf = new byte[256];
      	private int connect=0;
      	private PrintWriter outputstream;
      	private PrintWriter outputstreamTSC;
		private BufferedReader 	in;
		private BufferedReader 	inTSC;
      	private int Totalrow = 0;
	 	private int colmn=0;
	 	private int totalSocket=0;
	 	private int usersSelectedSocket=0;
      	private static JTable mytable;
        private int retry=0;
        private int addrow=0;
        private int SelRow=0;
        private String openFileName = "listname";
        private int SelCol=0;
       	private DataObject[][] data;
        private BufferedReader br;
        private String line;
        private String inetadd;
        private String SelectedUser="Send to: Username";
		private FileInputStream fis;
        private String servermessage=null;
		private String ClientName=null;
        private String ClientIPadress=null;
    	private String ServerUserToClientMessage=null;
    	private File file;
    	private JFileChooser filechoose = new JFileChooser();
    // End of variables declaration//GEN-END:variables
}
